package cron;

import api.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
//import com.alibaba.nacos.common.utils.RandomUtils;
import core.UpdataZingPwd;
import core.UpdatePassword;
import dao.ProxyConfig;
import dao.Result;
import utils.JsonUtil;
import utils.LoggerUtile;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

public class UpdateZingspeedPasswordTask {

    private static long startTime;
    private static int retryCount;
    private static int maxRetry;
    private static int reportRetryCount = 0;
    private static int proxyRetryCount;

    static String addr_security;
    static String addr_gamecenter;

    static String addr_uiautomator2;
    static ProxyConfig proxyConfig = new ProxyConfig();
    static Map accountInfo = new HashMap();

    static String[] errorMessages = {
            "Proxy connection timed out",
            "Socks5 proxy rejected connection",
            "Socks5 Authentication failed",
            "timeout of 30000ms exceeded",
            "read ECONNRESET",
            "connect ECONNREFUSED"
    };
    static LoggerUtile logger =LoggerUtile.getLogger("zingspeed-pwd-update");
    public static   void updateZingspeedPasswordTask(String port,String port2) {
        addr_security = port;
        addr_gamecenter = port2;
        // 实现updateZingspeedPasswordTask的逻辑
        logger.info("Executing updateZingspeedPasswordTask");
        Map<String, Object> body = new HashMap<>();
        body.put("changePlatform", 1);
        body.put("pageNum", 1);
        body.put("pageSize", 10);
        body.put("gameIds",new int[]{32773}); // Assuming config.getZingSpeedGameId() returns the appropriate data
        body.put("accessToken","5ad9ba4e4a18d81457c3a8286e134f05");
        String s = JSON.toJSONString(body);
        String response = null;
        response =new FetchNeedChangePwdAccountList().fetchNeedChangePwdAccountList(port,s);
        logger.info("请求zp改密任务列表结果"+response);
        /*
        请求zp改密任务列表结果{"status":1,"errcode":200,"msg":"success",
        "data":{"item":[{"orderId":"71586","haoId":"2616884","garenaAccount":"szdfwlaa","garenaPassword":"+MvyP4899","garenaKey":"Q3PMDZONH2WPDCR6"}]}}
         */
        JSONObject parse = (JSONObject) JSONObject.parse(response);
        JSONObject data = (JSONObject) parse.get("data");
        if(data == null){
            return;
        }
        fetchEmailAccount(data);
        // Handle the response data here and create Task objects as needed
    }

    public static void fetchEmailAccount(Object data){
        initdata();
        JSONObject datas1 = (JSONObject) JSONObject.parse(JSON.toJSONString(data));
        JSONArray item = (JSONArray) datas1.get("item");
        JSONObject datas = (JSONObject) item.get(0);
        /*
        datas{"garenaAccount":"szdfwlaa","garenaKey":"Q3PMDZONH2WPDCR6","garenaPassword":"+MvyP4899","haoId":"2616884","orderId":"71586"}
         */
        logger.info("datas"+datas);
        try {
            Map macc=new HashMap();
            macc.put("accountSeatId",datas.get("haoId"));
            String s1 = JSON.toJSONString(macc);
            String emailAccount= FetchAccountEmailAccount.fetchAccountEmailAccount(addr_gamecenter,s1);
            String emailPassword= FetchAccountEmailPassword.fetchAccountEmailPassword(addr_gamecenter,s1);
            accountInfo.put("garenaAccount",datas.get("garenaAccount"));
            accountInfo.put("haoId",datas.get("haoId"));
            accountInfo.put("orderId",datas.get("orderId"));
            if(!JsonUtil.isEmty(emailAccount)){
                accountInfo.put("emailAccount",emailAccount.trim());
            }
            if(!JsonUtil.isEmty(emailPassword)){
                accountInfo.put("emailPassword",emailPassword.trim());
            }
            if (JsonUtil.isEmty(emailAccount) || JsonUtil.isEmty(emailPassword)) {
                logger.info("未设置邮箱账号密码" +  emailAccount + emailPassword);
                Map m = new HashMap();
                m.put("nowPassword",null);
                m.put("data",null);
                handleCompleted(new Result(-2,"未设置邮箱账号密码",JSON.toJSONString(m)));
                return;
            }
            updatePassword();
        }catch (Exception e){
            logger.error("查询货架邮箱失败，结束任务" + e.getMessage());
            Map m = new HashMap();
            m.put("nowPassword",null);
            m.put("data",e);
            handleCompleted(new Result(-1,"查询货架邮箱失败",JSON.toJSONString(m)));
        }
    }

    static void fetchProxy(String dsip){
        try {
            Map<String, Object> body = new HashMap<>();
            body.put("proxyType", 1);
            body.put("accessToken","5ad9ba4e4a18d81457c3a8286e134f05");
            body.put("disableIp", (dsip!=null ? dsip : null));
            String response = FetchProxyIp.fetchProxyIp(addr_security, JSON.toJSONString(body));
            logger.info("代理查询结果" + response);
            JSONObject parse = (JSONObject) JSONObject.parse(response);
            proxyConfig.setIp((String) parse.get("ip"));
            proxyConfig.setPort((int) parse.get("port"));
            updatePassword();
        }catch (Exception e){

            proxyRetryCount++;

            // 代理查询请求异常重试
            if (proxyRetryCount < 10) {
                logger.info("代理IP查询失败,稍后重试" + e.getMessage() + proxyRetryCount);
                // 使用ScheduledExecutorService创建一个单线程的调度器
                ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
                // 调度一个任务以在指定延迟后运行
                scheduler.schedule(() -> fetchProxy(null), 3*1000, TimeUnit.MILLISECONDS);
                return;
            }

            logger.info("代理IP查询失败,重试结束" +e.getMessage());
            handleCompleted(new Result(-1,"代理IP查询异常",e.getMessage()));
        }
    }


    private static void updatePassword(){
        try{
            long l = System.currentTimeMillis();
            logger.info("开始处理任务" +  JSON.toJSONString(accountInfo));

            Map m = new HashMap();
            m.put("data",JSON.toJSONString(accountInfo));
            m.put("proxyConfig",JSON.toJSONString(proxyConfig));
            m.put("taskType",0);
            UpdataZingPwd.start(m,addr_uiautomator2).thenAccept(result -> {
                // Handle success here
                logger.info("任务处理完成" + result + "耗时"  +(System.currentTimeMillis() - l));
                retryCount++;
                JSONObject parse = (JSONObject) JSONObject.parse(JSON.toJSONString(result));
                int code = (int) parse.get("code");
                String error = (String) parse.get("error");
                if (code == -1 && retryCount < maxRetry) {
                    if (error!=null){
                        JSONObject error1 = (JSONObject) JSONObject.parse((String) parse.get("error"));
                        for (String errorMessage : errorMessages) {
                            errorMessage.contains((String)error1.get("message"));
                            logger.info("代理IP异常"  + JSON.toJSONString(proxyConfig));
                        }
                    }
                    logger.info("连接异常重试" + retryCount);
                    // this.fetchProxy(this.proxyConfig.ip)
                    updatePassword();
                    return;
                }
                handleCompleted(result);
            });
        }catch (Exception e){
            Map m = new HashMap();
            m.put("code",-1);
            m.put("message","'任务处理异常'");
            handleCompleted(JSON.toJSONString(m));
            logger.error("任务处理异常" +  e.getMessage());
        }
    }

    static void handleCompleted(Object o){
        try {
            long l = System.currentTimeMillis();
            String garenaAccount = (String) accountInfo.get("garenaAccount");
            String haoId = (String) accountInfo.get("haoId");
            String orderId = (String) accountInfo.get("orderId");

            Map<String, Object> formData = new HashMap<>();
            formData.put("changePlatform", 1);
            formData.put("garenaAccount", garenaAccount);
            formData.put("haoId", haoId);
            formData.put("orderId", orderId);
            JSONObject parse = (JSONObject) JSONObject.parse(JSON.toJSONString(o));
            formData.put("nowPassword", parse.get("nowPassword"));
            formData.put("message", parse.get("message"));
            formData.put("data", parse.get("data"));
            formData.put("code", parse.get("code"));
            String s = UpdateNeedChangePwdAccount.updateNeedChangePwdAccount(addr_security, JSON.toJSONString(formData));
            JSONObject parse1 = (JSONObject) JSONObject.parse(s);
            logger.info("更新处理结果完成" + parse1);
            logger.info("任务全程耗时"+ (System.currentTimeMillis() - l));

        }catch (Exception e){
            logger.error("更新处理结果请求异常,一分钟后重试" + e.getMessage());
            reportRetryCount ++;
            if (reportRetryCount < 3) {
                scheduleRetry(o, 5 * 60 * 1000);
             }
    }}
    public static void scheduleRetry(Object result, long delay) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                handleCompleted(result);
            }
        }, delay);
    }

    private static void initdata() {
        startTime = System.currentTimeMillis();
        retryCount = 0;
        maxRetry = 5;
        proxyRetryCount = 0;
    }

}

